//index.js
const app = getApp();
var call = require("../../utils/ajax.js")
Page({
  data: {
    BGIMG: "",
    URL: "",
    //样式1
    backgroundImg: 'http://video.xuanhei.top/poster1.png',
    //样式2
    backgroundImg1: 'http://video.xuanhei.top/poster2.png',
    //样式3
    backgroundImg2: 'http://video.xuanhei.top/poster3.png',
    
    //宠物图片
    petImg: 'https://pic.qqtn.com/up/2019-10/15704167881314038.jpg',
    petImg1: "https://pic.qqtn.com/up/2019-10/15704167881314038.jpg",
    //宠物二维码
    QRcode: "http://video.xuanhei.top/min.png",
    test: "小黑",
    petData: {
      imgurl: [],
      inform: {
        city_area: "漳州",
        contacts_phone: "12345678889",
        contacts_wechat: "xunahei",
        county_area: "鼓楼区",
        detailed_area: "百度新华街",
        pet_about_me: "很骚，喜欢打架，就是很想打架。",
        pet_adopt_condition: "要很完美哦。",
        pet_adopt_process: "点击“领养我”联系管理员-到基地带我回家",
        pet_age: "3岁",
        pet_category: "汪星人",
        pet_id: 74,
        pet_index: "1120f65a869446229f51942af2cddd62",
        pet_insects: "未驱虫",
        pet_name: "儿子",
        pet_picture: "1183997270398967808",
        pet_push_date: "2019-10-15",
        pet_sex: "男孩子",
        pet_state: "待领养",
        pet_sterilization: "已绝育",
        pet_vaccine: "已打疫苗",
        pet_varieties: "阿拉斯加",
        publisher_id: "ongjN4h6S8nS2alrYRcklUVCyQXY",
        publisher_img: "ongjN4h6S8nS2alrYRcklUVCyQXY/logo/协会唯一标识/1180960046820458496.png",
        publisher_name: "福建动物保护协会"
      }
    },
    BGNum: 1
  },

  onLoad: function (options) {
    let that = this;

    this.setData({
      URL: app.globalData.URL,
      BGIMG: this.data.backgroundImg
    })
    // let url = "SearchPet/createPoster/" + options.id;
    // let url = "Pet/selectOnePet?pet_id="+options.id;
    // call.getData1(url, function(res) {
    //   let img1 = {};
    //   let img2 = {};
    //   var kk = [];
    //   console.log(res)
    //   try{
    //     kk = res.data.imgurl;
    //     img1 = kk[0];
    //     img2 = kk[1];
    //     if(img1!=undefined&&img1!=""){
    //       wx.getImageInfo({
    //         src: that.data.URL+img1.path,
    //         success(res) {
    //           console.log(res)
    //           that.setData({
    //             petImg: res.path
    //           });
    //           if(img2!=undefined&&img2!=""){
    //             that.setData({
    //               petImg1: that.data.URL+img2.path
    //             });
    //           }else{
    //             that.setData({
    //               petImg1: res.path
    //             });
    //           }
    //         }
    //       })

    //     }
    //   }catch (e){
    //     wx.getImageInfo({
    //       src: that.data.URL+img1.path,
    //       success(res) {
    //         console.log(res)
    //         that.setData({
    //           petImg1: res.path
    //         });
    //       }
    //     })
    //   }
    //   setTimeout(function (){
    //     that.drawCanvas(res.data);
    //   },2000)

    // }, function() {

    // })
    setTimeout(function (){
      that.drawCanvas(that.data.petData);
    },2000)

  },
  //画图
  drawCanvas: function (petData) {
    let that = this;
    // let imgs = petData.imgurl;
    let messgae = petData.inform;
    console.log(messgae)

    console.log(petData)

    let ctx = wx.createCanvasContext('myCanvas');
    let ctxW = this.data.windowWidth;
    let ctxH = 1210;
    //初始化画布背景宽高及内容宽高变量
    var myCanvasWidth
    var myCanvasHeight
    //获取手机屏幕尺寸并给画布宽高赋值
    wx.getSystemInfo({
      success: function (res) {
        console.log(res)
        // myCanvasWidth = res.windowWidth - 56
        // myCanvasHeight = res.windowHeight - 100
        myCanvasWidth = res.windowWidth
        myCanvasHeight = res.windowHeight
      },
    })

    // 垂直渐变
    const grd = ctx.createLinearGradient(0, 0, 0, ctxH);
    grd.addColorStop(0, '#ffffff');
    grd.addColorStop(1, '#ffffff');
    ctx.setFillStyle(grd);
    ctx.fillRect(0, 0, ctxW, ctxH);

    //背景
    console.log(that.data.BGIMG);
    ctx.drawImage(that.data.BGIMG, myCanvasWidth * 0.025, myCanvasHeight * 0.03, myCanvasWidth * 0.95, myCanvasHeight * 0.95); //card
    ctx.restore(); //恢复之前保存的绘图上下文 继续绘制

    //宠物图片1
    let oneX = myCanvasWidth * 0.54;
    let oneY = myCanvasHeight * 0.35;
    let oneWidth = myCanvasWidth * 0.35;
    let oneHeight = myCanvasWidth * 0.5;
    ctx.save();
    that.canvasH(ctx, oneX, oneY, oneWidth, oneHeight, 20)
    // ctx.beginPath(); //开始绘制
    // ctx.rect(oneX, oneY, oneWidth, oneHeight) //边长为为xx的正方形
    // ctx.clip(); //剪切
    console.log(that.data.petImg)
    ctx.drawImage(that.data.petImg, oneX, oneY, oneWidth, oneHeight); //userHeader  // 推进去图片必须是https  
    ctx.restore(); //恢复之前保存的绘图上下文 继续绘制
    //宠物图片2
    let twoX = myCanvasWidth * 0.11;
    let twoY = myCanvasHeight * 0.5;
    let twoWidth = myCanvasWidth * 0.35;
    let twoHeight = myCanvasWidth * 0.5;
    ctx.save();
    that.canvasH(ctx, twoX, twoY, twoWidth, twoHeight, 20)
    console.log(that.data.petImg1)
    // ctx.drawImage(this.data.URL + petData.path, 28, 360, 180, 180); //userHeader  // 推进去图片必须是https
    ctx.drawImage(that.data.petImg1, twoX, twoY, twoWidth, twoHeight); //userHeader  // 推进去图片必须是https
    ctx.restore(); //恢复之前保存的绘图上下文 继续绘制

    //开始绘制宠物二维码
    let threeX = myCanvasWidth * 0.68;
    let threeY = myCanvasHeight * 0.7;
    let threeWidth = myCanvasWidth * 0.2;
    let threeHeight = myCanvasWidth * 0.2;
    ctx.save();
    ctx.beginPath(); //开始绘制
    ctx.rect(threeX, threeY, threeWidth, threeHeight) //边长为为10px的正方形

    ctx.clip(); //剪切
    ctx.drawImage(that.data.QRcode, threeX, threeY, threeWidth, threeHeight); //userHeader  // 推进去图片必须是https
    ctx.restore(); //恢复之前保存的绘图上下文 继续绘制

    //标题
    let titleX = myCanvasWidth * 0.4;
    let titleY = myCanvasHeight * 0.09;
    // let titleWidth = myCanvasWidth*0.2;
    // let titleHeight = myCanvasWidth*0.2;
    ctx.setTextAlign('left');
    ctx.setTextBaseline('middle');
    ctx.setFontSize(20);
    ctx.setFillStyle('black');
    ctx.fillText("萌宠资料", titleX, titleY);
    //名字
    let nameX = myCanvasWidth * 0.15;
    let nameY = myCanvasHeight * 0.17;

    ctx.setTextAlign('left');
    ctx.setTextBaseline('middle');
    ctx.setFontSize(18);
    ctx.setFillStyle('black');
    ctx.fillText("名字：" + messgae.pet_name, nameX, nameY);
    //年龄
    let ageX = myCanvasWidth * 0.15;
    let ageY = myCanvasHeight * 0.21;
    ctx.setTextAlign('left');
    ctx.setTextBaseline('middle');
    ctx.setFontSize(18);
    ctx.setFillStyle('black');
    ctx.fillText("年龄：" + messgae.pet_age, ageX, ageY);


    //品种
    let classX = myCanvasWidth * 0.15;
    let classY = myCanvasHeight * 0.25;

    ctx.setTextAlign('left');
    ctx.setTextBaseline('middle');
    ctx.setFontSize(18);
    ctx.setFillStyle('black');
    ctx.fillText("品种：" + messgae.pet_varieties, classX, classY);

    //宠物的故事
    let petX = myCanvasWidth * 0.15;
    let petY = myCanvasHeight * 0.29;

    ctx.setTextAlign('left');
    ctx.setTextBaseline('middle');
    ctx.setFontSize(18);
    ctx.setFillStyle('black');
    // ctx.fillText("特别叮嘱：", 28, 205, 320);
    var text1 = "特征：" + messgae.pet_about_me; //这是要绘制的文本
    that.drawText(ctx, text1, petX, petY, "", myCanvasWidth * 0.7);
    ctx.restore(); //恢复之前保存的绘图上下文 继续绘制
    /**/

    //是否打疫苗
    let jueX = myCanvasWidth * 0.45;
    let jueY = myCanvasHeight * 0.17;
    var discountText = messgae.pet_vaccine;

    var bdColor = 'red';
    var bdBackground = 'transparent';
    ctx.save();
    ctx.setFontSize(10);
    if(discountText=="未打疫苗"){
      bdColor = '#919191';
      ctx.setFillStyle('#919191');
    }else{
      ctx.setFillStyle('red');
    }
    ctx.setTextAlign('left');
    var bdRadius = 5;
    var textPadding = 8;
    var boxHeight = 18;
    var boxWidth = ctx.measureText(discountText).width + textPadding * 2;
    ctx.fillText(discountText, jueX, jueY);
    console.log(ctx.measureText(discountText).width)

    that.roundRect(ctx, jueX - 9, jueY - 10, boxWidth, boxHeight, bdRadius, bdBackground, bdColor)
    ctx.restore(); //恢复之前保存的绘图上下文 继续绘制
    //是否绝育
    jueX = myCanvasWidth * 0.63;
    jueY = myCanvasHeight * 0.17;
    discountText = messgae.pet_sterilization;
    bdColor = 'red';
    bdBackground = 'transparent';
    ctx.save();
    ctx.setFontSize(10);
    if(discountText=="未绝育"){
      bdColor = '#919191';
      ctx.setFillStyle('#919191');
    }else{
      ctx.setFillStyle('red');
    }
    ctx.setTextAlign('left');
    bdRadius = 5;
    textPadding = 8;
    boxHeight = 18;
    boxWidth = ctx.measureText(discountText).width + textPadding * 2;
    ctx.fillText(discountText, jueX, jueY);
    console.log(ctx.measureText(discountText).width)

    that.roundRect(ctx, jueX - 9, jueY - 10, boxWidth, boxHeight, bdRadius, bdBackground, bdColor)
    ctx.restore(); //恢复之前保存的绘图上下文 继续绘制
    //是否驱虫
    jueX = myCanvasWidth * 0.78;
    jueY = myCanvasHeight * 0.17;
    discountText = messgae.pet_insects;
    bdColor = 'red';
    bdBackground = 'transparent';
    ctx.save();
    ctx.setFontSize(10);
    if(discountText=="未驱虫"){
      bdColor = '#919191';
      ctx.setFillStyle('#919191');
    }else{
      ctx.setFillStyle('red');
    }
    ctx.setTextAlign('left');
    bdRadius = 5;
    textPadding = 8;
    boxHeight = 18;
    boxWidth = ctx.measureText(discountText).width + textPadding * 2;
    ctx.fillText(discountText, jueX, jueY);
    console.log(ctx.measureText(discountText).width)

    that.roundRect(ctx, jueX - 9, jueY - 10, boxWidth, boxHeight, bdRadius, bdBackground, bdColor)
    ctx.restore(); //恢复之前保存的绘图上下文 继续绘制
    // ctx.stroke();//增加边框
    ctx.draw();




  },
  //文本换行 参数：1、canvas对象，2、文本 3、距离左侧的距离 4、距离顶部的距离 5、6、文本的宽度
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 18; //16为字体的高度
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight + 2);
      }
    }
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight
  },
  fo: function () {
    wx.showModal({
      title: '提示',
      content: '您输入的shoujihao有误',
    })
    // wx.showToast({
    //   title: '成功',
    // })
  },
  //画圆角边框
  roundRect(ctx, x, y, w, h, r, fillColor, strokeColor) {
    // 画圆角 ctx、x起点、y起点、w宽度、y高度、r圆角半径、fillColor填充颜色、strokeColor边框颜色
    // 开始绘制
    ctx.beginPath()

    // 绘制左上角圆弧 Math.PI = 180度
    // 圆心x起点、圆心y起点、半径、以3点钟方向顺时针旋转后确认的起始弧度、以3点钟方向顺时针旋转后确认的终止弧度
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

    // 绘制border-top
    // 移动起点位置 x终点、y终点
    ctx.moveTo(x + r, y)
    // 画一条线 x终点、y终点
    ctx.lineTo(x + w - r, y)
    // ctx.lineTo(x + w, y + r)

    // 绘制右上角圆弧
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

    // 绘制border-right
    ctx.lineTo(x + w, y + h - r)
    // ctx.lineTo(x + w - r, y + h)

    // 绘制右下角圆弧
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

    // 绘制border-bottom
    ctx.lineTo(x + r, y + h)
    // ctx.lineTo(x, y + h - r)

    // 绘制左下角圆弧
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

    // 绘制border-left
    ctx.lineTo(x, y + r)
    // ctx.lineTo(x + r, y)

    if (fillColor) {
      // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
      ctx.setFillStyle(fillColor)
      // 对绘画区域填充
      ctx.fill()
    }

    if (strokeColor) {
      // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
      ctx.setStrokeStyle(strokeColor)
      // 画出当前路径的边框
      ctx.stroke()
    }
    // 关闭一个路径
    ctx.closePath()

    // 剪切，剪切之后的绘画绘制剪切区域内进行，需要save与restore
    ctx.clip()
    // ctx.save();
    // ctx.restore(); //恢复之前保存的绘图上下文 继续绘制
  },
  //分享图片
  shareImage: function () {
    this.onShareAppMessage();
  },
  //换个样式
  changStyle: function () {
    let that = this;
    let num = this.data.BGNum;
    console.log(num)
    if (num === 2) {
      that.setData({
        BGIMG: that.data.backgroundImg2,
        BGNum: 0
      })
      setTimeout(function (){
        that.drawCanvas(that.data.petData);
      },2000)
    } else {
      if (num === 0) {
        that.setData({
          BGIMG: that.data.backgroundImg
        })
        setTimeout(function (){
          that.drawCanvas(that.data.petData);
        },2000)
      }
      if (num === 1) {
        that.setData({
          BGIMG: that.data.backgroundImg1
        })
        setTimeout(function (){
          that.drawCanvas(that.data.petData);
        },2000)
      }
      that.setData({
        BGNum: that.data.BGNum + 1
      })
    }

  },
  // 保存图片
  saveImage: function (e) {
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: function (res) {
        console.log(res)
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            console.log(res)
            wx.showToast({
              title: '图片保存成功',
              icon: 'success',
              duration: 2000
            })
          },
          fail(res) {
            console.log(res)
            if (res.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("用户一开始拒绝了，我们想再次发起授权")
              console.log('打开设置窗口')
              wx.openSetting({
                success(settingdata) {
                  console.log(settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                  } else {
                    console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                  }
                }
              })
            }
          },
          complete(res) {
            console.log(res)
          }
        })
      }
    })
  },
  onShareAppMessage: function (res) {
    return {
      title: "这个是我分享出来的东西",
      success: function (res) {
        console.log(res, "转发成功")
      },
      fail: function (res) {
        console.log(res, "转发失败")
      }
    }
  },
  /**
 * 
 * @param {CanvasContext} ctx canvas上下文
 * @param {number} x 圆角矩形选区的左上角 x坐标
 * @param {number} y 圆角矩形选区的左上角 y坐标
 * @param {number} w 圆角矩形选区的宽度
 * @param {number} h 圆角矩形选区的高度
 * @param {number} r 圆角的半径
 */
  canvasH: function (ctx, x, y, w, h, r) {
    // 开始绘制
    ctx.beginPath()
    // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
    // 这里是使用 fill 还是 stroke都可以，二选一即可
    ctx.setFillStyle('transparent')
    // ctx.setStrokeStyle('transparent')
    // 左上角
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

    // border-top
    ctx.moveTo(x + r, y)
    ctx.lineTo(x + w - r, y)
    ctx.lineTo(x + w, y + r)
    // 右上角
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

    // border-right
    ctx.lineTo(x + w, y + h - r)
    ctx.lineTo(x + w - r, y + h)
    // 右下角
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

    // border-bottom
    ctx.lineTo(x + r, y + h)
    ctx.lineTo(x, y + h - r)
    // 左下角
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

    // border-left
    ctx.lineTo(x, y + r)
    ctx.lineTo(x + r, y)

    // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
    ctx.fill()
    // ctx.stroke()
    ctx.closePath()
    // 剪切
    ctx.clip()
  }
})